package com.zx.wangyixinwen;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.zx.wangyixinwen.activity.MyBaseApplication;

/**
 * Created by dllo on 16/1/13.
 */
public class MyRequestQueue {
    private volatile static RequestQueue queue;
    private volatile static ImageLoader loader;


    private static MyMemoryCache cache;

    private MyRequestQueue() {
    }

    public static RequestQueue getQueue() {
        if (queue == null) {
            queue = Volley.newRequestQueue(MyBaseApplication.getContext());
        }
        return queue;
    }

    public static void addRequest(Request request) {
        getQueue().add(request);
    }

    public static ImageLoader getLoader() {
        if (loader == null) {
            loader = new ImageLoader(getQueue(), getCache());
        }
        return loader;
    }


    public static MyMemoryCache getCache() {
        if (cache == null) {
            cache = new MyMemoryCache();
        }
        return cache;
    }

    public static void setNetImage(NetworkImageView networkImageView, String url) {
        networkImageView.setDefaultImageResId(R.mipmap.refresh);
        networkImageView.setErrorImageResId(R.mipmap.refresh);
        networkImageView.setImageUrl(url, getLoader());
    }

    private static class MyMemoryCache implements ImageLoader.ImageCache {


        private LruCache<String, Bitmap> cache = new LruCache<>(20 * 1024 * 1024);

        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    }


}
